package kanboard

import (
	kanboard "gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/business/dao/kanboard"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/entity"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/model"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/util"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"net/http"
	"time"
)

const (
	//time_format = "2006-01-02 15:04:05"
	time_format    = "2006-01-02"
	defautDuration = 30 //默认查询时间30天
)

func GetKanboard(c *gin.Context) {
	reqParam := entity.RequestKanboardParam{}
	var startTime, endTime time.Time
	var startParse, endParse error
	if err := c.BindWith(&reqParam, binding.Form); err != nil {
		global.Log.Sugar().Error("参数错误", err)
		c.JSON(http.StatusOK, model.Fail("参数错误"))
		return
	}
	if reqParam.StartTime != "" {
		startTime, startParse = time.Parse(time_format, reqParam.StartTime)
	}
	if reqParam.EndTime != "" {
		endTime, endParse = time.Parse(time_format, reqParam.EndTime)
	}

	if startParse != nil || endParse != nil {
		global.Log.Sugar().Error("查询条件异常")
		c.JSON(http.StatusOK, model.Fail("查询条件异常,请检查时间参数"))
		return
	}
	if reqParam.StartTime != "" && reqParam.EndTime != "" && startTime.After(endTime) {
		global.Log.Sugar().Error("查询条件异常")
		c.JSON(http.StatusOK, model.Fail("查询条件异常,开始时间晚于结束时间"))
		return
	}
	//查询条件默认为一个月
	if startTime.IsZero() {
		startTime = util.TodayDiff(defautDuration)
	}
	if endTime.IsZero() {
		endTime = util.TodayDiff(-1)
	} else {
		endTime = util.TimeDiff(endTime, -1)
	}
	kb, err := kanboard.GetKanboardInfo(startTime, endTime)
	if err != nil {
		global.Log.Sugar().Error("获取数据看板失败", err)
		c.JSON(http.StatusOK, model.Fail("获取数据看板失败"))
		return
	}
	c.JSON(http.StatusOK, model.SuccessObject("操作成功", kb))
}
